﻿using System;
using System.ComponentModel.Composition;
using System.Configuration;
using System.Linq;
using System.Net.Mail;

namespace AxeFrog.Net.Mail
{
	[Export]
	public class Mailer
	{
		private IMailSender _mailer;
		[ImportingConstructor]
		public Mailer([ImportMany] Lazy<IMailSender, IMailSenderMetadata>[] mailSenders)
		{
			var cfg = ConfigurationManager.AppSettings["MailSender.Default"] ?? "Default";
			var mailer = mailSenders.Where(m => m.Metadata.Name == cfg).FirstOrDefault();
			if(mailer != null)
				_mailer = mailer.Value;
		}

		public void Send(MailAddress sender, MailAddress recipient, string subject, string body, bool isTimeCritical)
		{
			_mailer.Send(sender, recipient, subject, body, isTimeCritical);
		}

		public void Send(MailAddress recipient, string subject, string body, bool isTimeCritical)
		{
			var name = ConfigurationManager.AppSettings["MailSender.DefaultFrom.Name"];
			var email = ConfigurationManager.AppSettings["MailSender.DefaultFrom.Email"];
			var sender = new MailAddress(email, name);
			_mailer.Send(sender, recipient, subject, body, isTimeCritical);
		}

		public void Send(string recipientEmail, string subject, string body, bool isTimeCritical)
		{
			Send(new MailAddress(recipientEmail), subject, body, isTimeCritical);
		}

		public void Send(string recipientName, string recipientEmail, string subject, string body, bool isTimeCritical)
		{
			Send(new MailAddress(recipientEmail, recipientName), subject, body, isTimeCritical);
		}
	}
}
